<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item prop="supplierName" label="供应商名称">
            <el-input
              v-model="baTable.form.items!.supplierName"
              type="string"
              placeholder="供应商名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="供应商类型" prop="supplierType">
            <el-tree-select
              v-model="baTable.form.items!.supplierType"
              :data="state.supplierTypeOptions"
              check-strictly
              :props="{
                label: 'dictLabel',
                value: 'dictValue',
                children: 'children',
              }"
              :render-after-expand="false"
            />
          </el-form-item>
          <el-form-item prop="addr" label="供应商地址">
            <el-input
              v-model="baTable.form.items!.address"
              type="string"
              placeholder="输入详细地址后(精确到号)"
              @blur="getAddr"
            ></el-input>
            <div class="block-help">{{ state.coordinate }}</div>
          </el-form-item>
          <!-- <el-form-item prop="creditCode" label="企业社会信用代码">
            <el-input
              v-model="baTable.form.items!.creditCode"
              type="string"
              placeholder="企业社会信用代码"
            ></el-input>
          </el-form-item> -->
          <FormItem
            label="供应商状态"
            v-model="baTable.form.items!.supplierStatus"
            type="radio"
            prop="supplierStatus"
            :data="{
              content: { 0: '无效', 1: '正常' },
              childrenAttr: { border: true },
            }"
          />
          <el-form-item prop="contact" label="联系人">
            <el-input
              v-model="baTable.form.items!.contact"
              type="string"
              placeholder="联系人"
            ></el-input>
          </el-form-item>
          <el-form-item prop="contactNumber" label="联系方式">
            <el-input
              v-model="baTable.form.items!.contactNumber"
              type="string"
              placeholder="联系电话"
            ></el-input>
          </el-form-item>
          <el-form-item prop="wechat" label="微信号">
            <el-input
              v-model="baTable.form.items!.wechat"
              type="string"
              placeholder="微信号"
            ></el-input>
          </el-form-item>
          <el-form-item prop="qq" label="QQ号">
            <el-input
              v-model="baTable.form.items!.qq"
              type="string"
              placeholder="QQ号"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref, inject, onMounted, watch, nextTick } from "vue";
import type baTableClass from "@/utils/baTable";
import type { ElForm, FormItemRule, FormRules, ElTree } from "element-plus";
import FormItem from "@/components/formItem/index.vue";
import { useBusiness } from "@/store/backend/BusinessM/info";
import { useRegion } from "@/store/backend/SysM/region";
import { getPointByAddress } from "vue-baidu-map-3x"; //baidu-map组件red
import { getDictData } from "@/utils/common"; // 导入表格api方法生成器
import { ElNotification } from "element-plus"; //处理导航信息

const formRef = ref<InstanceType<typeof ElForm>>();
const baTable = inject("baTable") as baTableClass;
const dictionary = inject("dictionary") as any;
const business = useBusiness();
const region = useRegion();
const treeRef = ref<InstanceType<typeof ElTree>>();

const state: {
  regionOptions: anyObj[];
  supplierTypeOptions: anyObj[];
  supplierStatusOptions: anyObj[];
  coordinate: any;
} = reactive({
  regionOptions: [], //区域列表
  supplierTypeOptions: [], //供应商类型列表
  supplierStatusOptions: [], //供应商类型列表
  coordinate: "", //经纬度
});

const props = {
  label: "areaName",
  value: "areaId",
  children: "children",
};

const rules = reactive<FormRules>({
  supplierName: [
    { required: true, message: "供应商名称不能为空", trigger: "blur" },
  ],
  //   region: [
  //     {
  //       required: true,
  //       validator: (rule: any, val: string, callback: Function) => {
  //         let ids = getCheckeds();
  //         if (ids.length <= 0) {
  //           return callback(new Error("请选择区域"));
  //         }
  //         return callback();
  //       },
  //     },
  //   ],
  supplierType: [
    { required: true, message: "供应商类型不能为空", trigger: "blur" },
  ],
  supplierStatus: [
    { required: true, message: "供应商状态不能为空", trigger: "blur" },
  ],
  contact: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
  contactNumber: [
    {
      required: true,
      message: "联系电话不能为空",
      trigger: "blur",
    },
    {
      validator: function (rule, value, callback) {
        if (/^1[34578]\d{9}$/.test(value) == false) {
          callback(new Error("手机号格式错误"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

const handleCheckChange = (data: any, node: any) => {
  console.log("data", data, "node", node);
  baTable.form.items!.regionName = data.areaName;
};

//地址转换为坐标
const getAddr = () => {
  getPointByAddress(
    {
      address: baTable.form.items!.address,
    },
    ["wZcU7ugfOpZLuuRTAvNPn3Y36rpFxp1Q"]
  )
    .then((res) => {
      let { location, formatted_address } = res as any;
      console.log("坐标", location);
      baTable.form.items!.lat = JSON.stringify(location.lat);
      baTable.form.items!.lon = JSON.stringify(location.lng);
      state.coordinate = JSON.stringify(location);
    })
    .catch((err: any) => {
      console.log(err);
      ElNotification({
        type: "warning",
        message: err + ",请检查并填写正确供应商地址",
      });
      baTable.form.items!.address = "";
      baTable.form.items!.coordinate = "";
    });
};

//包含所有的层级id
const getCheckeds = () => {
  return treeRef
    .value!.getCheckedKeys()
    .concat(treeRef.value!.getHalfCheckedKeys());
};
//获取最后一级id
const getCheckedOne = () => {
  return treeRef.value!.getCheckedKeys();
};

//获取供应商类型字典
const getMenuStatus = () => {
  //供应商类型
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["supplierType"])
  ) {
    dictionary.getDictInfo("sys_supplier_type").then((res: any) => {
      dictionary.moreTags["supplierType"] = getDictData(res);
      dictionary.moreTags["supplierTypeOrigin"] = res;
    });
  } else {
    state.supplierTypeOptions = dictionary.moreTags["supplierTypeOrigin"];
  }
  //供应商状态
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["supplierStatus"])
  ) {
    dictionary.getDictInfo("sys_supplie_status").then((res: any) => {
      dictionary.moreTags["supplierStatus"] = getDictData(res);
      dictionary.moreTags["supplierStatusOrigin"] = res;
    });
  } else {
    state.supplierStatusOptions = dictionary.moreTags["supplierStatusOrigin"];
  }
};
//获取部门类型字典
getMenuStatus();

onMounted(() => {});
// watch(
//   () => baTable.form.operate,
//   (newValue, oldValue) => {
//     console.log("newValue", newValue);
//     if (newValue === "add") {
//       nextTick(() => {
//         treeRef.value!.setCheckedKeys([], false);
//       });
//     }
//   },
//   {
//     immediate: true, // 值如果是true会打开首次监听
//   }
// );
defineExpose({
  getCheckeds,
  getCheckedOne,
});
</script>
<style lang="scss" scoped>
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
</style>
